<template>
  <div style="padding-top: 20px">
    <Select
      v-model="province"
      style="width: 200px"
      clearable
    >
      <Option
        v-for="item in provinceList"
        :value="item.code"
        :key="item.code"
        >{{ item.name }}</Option
      >
    </Select>
    <Select
      v-model="city"
      style="width: 200px"
      clearable
      :disabled="!province"
    >
      <Option
        v-for="item in cityList"
        :value="item.code"
        :key="item.code"
        >{{ item.name }}</Option
      >
    </Select>
    <Select
      v-model="area"
      style="width: 200px"
      clearable
      :disabled="!city"
    >
      <Option
        v-for="item in areaList"
        :value="item.code"
        :key="item.code"
        >{{ item.name }}</Option
      >
    </Select>
  </div>
</template>

<script lang="ts">
const EMITS_AREA_CHANGE = 'areaChange'
</script>

<script setup lang="ts">
import allAreas from '../lib/pca-code.json'
import { ref, watch } from 'vue'
interface AreaItem {
  name: string
  code: string
  children?: AreaItem[]
}

// 定义事件分发
const emits = defineEmits(['areaChange'])

// 省份
const province = ref('')
// 城市
const city = ref('')
// 区域
const area = ref('')

const provinceList = ref<AreaItem[]>(allAreas)
const cityList = ref<AreaItem[]>([])
const areaList = ref<AreaItem[]>([])

// 监听province
watch(
  () => province.value,
  (newVal) => {
    if (!newVal) cityList.value = []
    else {
      const cityLists = provinceList.value.find(
        (item) => item.code === newVal
      )!.children
      cityList.value = cityLists!
    }
    city.value = ''
    area.value = ''
  }
)

// 监听city
watch(
  () => city.value,
  (val) => {
    if (!val) areaList.value = []
    else {
      const areaLists = cityList.value.find(
        (item) => item.code === city.value
      )!.children
      areaList.value = areaLists!
    }
    area.value = ''
  }
)

// 监听area分发事件
watch(
  () => area.value,
  (val) => {
    let provinceData = {
      name: provinceList.value.filter((item) => item.code === province.value)[0]
        .name,
      code: province.value
    }
    let cityData = {
      name: cityList.value.filter((item) => item.code === city.value)[0].name,
      code: city.value
    }
    let areaData = {
      name: areaList.value.find((item) => item.code === area.value)!.name,
      code: val
    }
    emits(EMITS_AREA_CHANGE, {
      province: provinceData,
      city: cityData,
      area: areaData
    })
  }
)
</script>

<style scoped>
.ivu-select {
  margin-left: 20px;
}
</style>
